package cn.iocoder.mall.promotion.application.controller.admins;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.common.framework.util.DateUtil;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.common.utils.common.api.vo.Result;
import cn.iocoder.common.utils.common.system.util.JwtUtil;
import cn.iocoder.common.utils.common.util.ObjectUtils;
import cn.iocoder.mall.product.api.ProductSpuService;
import cn.iocoder.mall.product.api.bo.ProductSpuBO;
import cn.iocoder.mall.promotion.api.CouponService;
import cn.iocoder.mall.promotion.api.bo.CouponCardSBO;
import cn.iocoder.mall.promotion.api.bo.CouponPageBO;
import cn.iocoder.mall.promotion.api.bo.CouponTemplateBO;
import cn.iocoder.mall.promotion.api.bo.CouponTemplatePageBO;
import cn.iocoder.mall.promotion.api.dto.*;
import cn.iocoder.mall.promotion.application.convert.CouponCardConvert;
import cn.iocoder.mall.promotion.application.convert.CouponTemplateConvert;
import cn.iocoder.mall.promotion.application.vo.admins.AdminsCouponPageVO;
import cn.iocoder.mall.promotion.application.vo.admins.AdminsCouponTemplatePageVO;
import cn.iocoder.mall.promotion.application.vo.admins.AdminsCouponTemplateVO;
import cn.iocoder.mall.promotion.application.vo.coupon.CouponCardVO;
import cn.iocoder.mall.shop.api.ShopService;
import cn.iocoder.mall.shop.api.pojo.ShopDTO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.common.framework.vo.CommonResult.success;

@RestController
@RequestMapping("/admins/coupon")
@Api("优惠劵（码）模块")
public class AdminsCouponController {

    @Reference(validation = "true", version = "${dubbo.provider.CouponService.version}")
    private CouponService couponService;

    @Reference(validation = "true", version = "${dubbo.consumer.ShopService.version}")
    private ShopService shopService;

    @Reference(validation = "true", version = "${dubbo.consumer.ProductSpuService.version}")
    private ProductSpuService productSpuService;

    // ========== 优惠劵（码）模板 ==========

    @GetMapping("/template/page")
    @ApiOperation(value = "优惠劵（码）模板分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型", example = "参考 CouponTemplateTypeEnum 枚举"),
            @ApiImplicitParam(name = "title", value = "标题，模糊匹配", example = "活动 A"),
            @ApiImplicitParam(name = "status", value = "状态", example = "参考 CouponTemplateStatusEnum 枚举"),
            @ApiImplicitParam(name = "preferentialType", value = "优惠类型", example = "参考 CouponTemplatePreferentialTypeEnum 枚举"),
            @ApiImplicitParam(name = "pageNo", value = "页码，从 1 开始", example = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, example = "10"),
    })
    public Result<?> templatePage(@RequestParam(value = "type", required = false) Integer type,
                                                           @RequestParam(value = "title", required = false) String title,
                                                           @RequestParam(value = "status", required = false) Integer status,
                                                           @RequestParam(value = "preferentialType", required = false) Integer preferentialType,
                                                           @RequestParam(value = "pageNo", defaultValue = "0") Integer pageNo,
                                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        CouponTemplatePageBO result = couponService.getCouponTemplatePage(new CouponTemplatePageDTO()
                .setType(type).setTitle(title).setStatus(status).setPreferentialType(preferentialType)
                .setPageNo(pageNo).setPageSize(pageSize));
        IPage page=new Page<>();
        AdminsCouponTemplatePageVO vo=CouponTemplateConvert.ADMINS.convertPage(result);
        page.setTotal(vo.getTotal());
        page.setSize(pageSize);
        page.setTotal(pageNo);
        page.setRecords(vo.getList());
        return Result.ok(page);

    }


    @PostMapping("/template/addCard")
    @ApiOperation(value = "创建优惠劵模板")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "标题", required = true, example = "优惠劵牛逼"),
            @ApiImplicitParam(name = "description", value = "使用说明", example = "我只是描述"),
            @ApiImplicitParam(name = "quota", value = "每人限领个数", required = true),
            @ApiImplicitParam(name = "total", value = "发行总量"),
            @ApiImplicitParam(name = "priceAvailable", value = "是否设置满多少金额可用，单位：分", example = "0-不限制；大于0-多少金额可用"),
            @ApiImplicitParam(name = "rangeType", value = "可用范围的类型", required = true, example = "参见 CouponTemplateRangeTypeEnum 枚举"),
            @ApiImplicitParam(name = "rangeValues", value = "指定商品 / 分类列表，使用逗号分隔商品编号"),
            @ApiImplicitParam(name = "dateType", value = "生效日期类型", example = "参见 CouponTemplateDateTypeEnum 枚举"),
            @ApiImplicitParam(name = "validStartTime", value = "固定日期-生效开始时间", example = "当 dateType 为固定日期时，非空"),
            @ApiImplicitParam(name = "validEndTime", value = "固定日期-生效结束时间", example = "当 dateType 为固定日期时，非空"),
            @ApiImplicitParam(name = "fixedBeginTerm", value = "领取日期-开始天数", example = "当 dateType 为领取日期时，非空"),
            @ApiImplicitParam(name = "fixedEndTerm", value = "领取日期-结束天数", example = "当 dateType 为领取日期时，非空"),
            @ApiImplicitParam(name = "preferentialType", value = "优惠类型", example = "参见 CouponTemplatePreferentialTypeEnum 枚举"),
            @ApiImplicitParam(name = "priceOff", value = "优惠金额，单位：分", example = "当 preferentialType 为现金券时，非空"),
            @ApiImplicitParam(name = "percentOff", value = "折扣百分比", example = "当 preferentialType 为折扣卷时，非空"),
            @ApiImplicitParam(name = "discountPriceLimit", value = "折扣上限", example = "当 preferentialType 为折扣卷时，非空"),
    })
    public CommonResult<AdminsCouponTemplateVO> templateCardAdd(@RequestBody AdminsCouponTemplateVO templateVO) {
        // 创建 CouponCardTemplateAddDTO 对象
        templateVO.setValidStartTime(DateUtil.getDayBegin(templateVO.getValidStartTime())) ; // 开始时间，以当前 00:00:00 为准
        templateVO.setValidEndTime(DateUtil.getDayBegin(templateVO.getValidEndTime())) ; // 开始时间，以当前 00:00:00 为准
        CouponCardTemplateAddDTO couponCardTemplateAddDTO = ObjectUtils.copyObject(templateVO,CouponCardTemplateAddDTO.class);
        // 提交请求
        CouponTemplateBO result = couponService.addCouponCardTemplate(couponCardTemplateAddDTO);
        // 返回结果
        return success(CouponTemplateConvert.ADMINS.convert(result));
    }

    @PostMapping("/template/update_card")
    @ApiOperation(value = "更新优惠劵模板")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1"),
            @ApiImplicitParam(name = "title", value = "标题", required = true, example = "优惠劵牛逼"),
            @ApiImplicitParam(name = "description", value = "使用说明", example = "我只是描述"),
            @ApiImplicitParam(name = "quota", value = "每人限领个数", required = true),
            @ApiImplicitParam(name = "total", value = "发行总量"),
            @ApiImplicitParam(name = "rangeType", value = "可用范围的类型", required = true, example = "参见 CouponTemplateRangeTypeEnum 枚举"),
            @ApiImplicitParam(name = "rangeValues", value = "指定商品 / 分类列表，使用逗号分隔商品编号"),
    })
    public CommonResult<Boolean> templateCardUpdate(@RequestBody AdminsCouponTemplateVO templateVO) {
        // 创建 CouponCardTemplateAddDTO 对象
        CouponCardTemplateUpdateDTO couponCardTemplateUpdateDTO = ObjectUtils.copyObject(templateVO,CouponCardTemplateUpdateDTO.class);
        return success(couponService.updateCouponCardTemplate(couponCardTemplateUpdateDTO));
    }

    @PostMapping("/template/update_status")
    @ApiOperation(value = "更新优惠劵（码）模板状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "Banner 编号", required = true, example = "1"),
            @ApiImplicitParam(name = "status", value = "状态。1 - 开启；2 - 禁用", required = true, example = "1"),
    })
    public CommonResult<Boolean> templateUpdateStatus(@RequestParam("id") Integer id,
                                                      @RequestParam("status") Integer status) {
        return success(couponService.updateCouponTemplateStatus(JwtUtil.getUserIdByToken(), id, status));
    }


    @GetMapping("/template/getById")
    public Result<?> getTemplateById(@RequestParam Integer id){
        CouponTemplateBO bo=couponService.getCouponTemplate(id);
        AdminsCouponTemplateVO adminsCouponTemplateVO=ObjectUtils.copyObject(bo,AdminsCouponTemplateVO.class);
        if (bo!=null){
            CommonResult<ShopDTO> commonResult= shopService.getOneShopInfoByShopId(bo.getShopId());
            if (commonResult.isSuccess()){
                adminsCouponTemplateVO.setShopName(commonResult.getData().getShopName());
            }
            if (StrUtil.isNotBlank(bo.getRangeValues())){
                ArrayList arrayList=new ArrayList();
                String[] s=bo.getRangeValues().split(",");
                for (String temp:s){
                    arrayList.add(temp);
                }
               List<ProductSpuBO> list = productSpuService.getProductSpuList(arrayList);
                adminsCouponTemplateVO.setGoodsName(list.stream().map(ProductSpuBO::getName).collect(Collectors.toList()));
            }
        }

        return Result.ok(adminsCouponTemplateVO);
    }


    @DeleteMapping(value = "/template/delete")
    public Result<?> deleteCouponTemplateById(@RequestParam(name = "id", required = true) Integer id) {
        try {
            couponService.deleteCouponTemplateById(id);
        } catch (Exception e) {
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<?> result = new Result();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.couponService.deleteCouponTemplateByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }
    // ========== 优惠劵 ==========
    @GetMapping("/coupon/page")
    @ApiOperation(value = "优惠劵（码）模板分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "takeType", value = "类型", example = "参考 CouponTemplateTypeEnum 枚举"),
            @ApiImplicitParam(name = "title", value = "标题，模糊匹配", example = "活动 A"),
            @ApiImplicitParam(name = "status", value = "状态", example = "参考 CouponTemplateStatusEnum 枚举"),
            @ApiImplicitParam(name = "preferentialType", value = "优惠类型", example = "参考 CouponTemplatePreferentialTypeEnum 枚举"),
            @ApiImplicitParam(name = "pageNo", value = "页码，从 1 开始", example = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, example = "10"),
    })
    public Result<?> examplePage(@RequestParam(value = "takeType", required = false) Integer takeType,
                                 @RequestParam(value = "title", required = false) String title,
                                 @RequestParam(value = "status", required = false) Integer status,
                                 @RequestParam(value = "preferentialType", required = false) Integer preferentialType,
                                 @RequestParam(value = "pageNo", defaultValue = "0") Integer pageNo,
                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){
        CouponPageBO result =couponService.getCouponExamplePage(new CouponPageDTO()
                .setTakeType(takeType).setTitle(title).setStatus(status).setPreferentialType(preferentialType)
                .setPageNo(pageNo).setPageSize(pageSize).setIsDelete(0));
        IPage page=new Page<>();
        AdminsCouponPageVO vo= CouponCardConvert.ADMINS.convertPage(result);
        page.setTotal(vo.getTotal());
        page.setSize(pageSize);
        page.setRecords(vo.getList());
        return Result.ok(page);

    }
    @GetMapping("/coupon/getCouponInfo")
    public Result<?> getCouponInfo(@RequestParam(name="id") String id){
        CouponCardSBO couponCardSBO=couponService.getCouponInfo(id);
        return Result.ok(couponCardSBO);
    }
    @PostMapping("/coupon/add")
    public Result<?> couponAdd(@RequestBody CouponCardVO couponCardVO){
        CouponCardSDTO couponCardSDTO = ObjectUtils.copyObject(couponCardVO, CouponCardSDTO.class);
        try {
            couponCardSDTO.setCreateTime(new Date());
            couponCardSDTO.setIsDelete(0);
            couponService.save(couponCardSDTO);
        } catch (Exception e) {
            return Result.error("添加失败!");
        }
        return Result.ok("添加成功！");
    }
    @DeleteMapping("/coupon/delete")
    public Result<?> conponDelete(@RequestParam(name = "id", required = true) Integer id){
        try {
            couponService.deleteCouponById(id);
        } catch (Exception e) {
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }
    @DeleteMapping("/coupon/deleteBatch")
    public Result<?> coupondeleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<?> result = new Result();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.couponService.deleteCouponByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }




    // ========== 优惠码 ==========

}
